package com.ckzp.jfinal.system.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.ckzp.core.ConfigUtil;
import com.ckzp.core.Results;
import com.ckzp.core.id.UUIDHex;
import com.ckzp.core.json.JsonResult;
import com.ckzp.core.lc.Aes;
import com.ckzp.core.lc.Md5;
import com.ckzp.core.lc.Pwd;
import com.ckzp.core.model.Datas;
import com.ckzp.core.util.*;
import com.ckzp.jfinal.interceptor.Admins;
import com.ckzp.jfinal.system.WebSite;
import com.ckzp.jfinal.system.model.SysUser;
import com.ckzp.jfinal.system.model.SysWorklog;
import com.ckzp.jfinal.system.po.WebUser;
import com.ckzp.plugins.ip.IpKit;
import com.jfinal.aop.Clear;
import com.jfinal.log.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by 51594 on 2022/7/28.
 */
public class LoginUtil {

    /**
     * JWT过期时间
     * 默认 6小时
     */
    public static long EXPRESS_LOGIN_TIME = 1000 * 60 * 60 * 6 * 24;


    public static Log log = Log.getLog(LoginUtil.class);


    public static LoginUtil getInstance() {
        return new LoginUtil();
    }


    public static LoginUtil n() {
        return new LoginUtil();
    }

    public WebUser getWebUser(String empid) {
        SysUser su = SysUser.dao.findById(empid);
        WebUser wu = new WebUser();
        wu.setLoginID(su.mod.getStr("login_id"));
        wu.setEmpName(su.mod.getStr("user_name"));
        wu.setEmpID(su.mod.getStr("emp_id"));
        wu.setUser_type(su.mod.getStr("user_TYPE"));
        //
        String[] roles = getUserRole(wu.getEmpID());
        wu.setRoles(roles);
        return wu;
    }


    /**
     * 验证帐号密码
     *
     * @param request
     * @return
     */

    public boolean validateUserPwd(HttpServletRequest request) {
        String login_id = ParamUtil.getString(request, "username");
        String password = Md5.MD5(ParamUtil.getString(request, "password"));
        String sql = "select * from sys_user where login_id=? and user_pwd=?";
        SysUser su = SysUser.dao.findFirst(sql, login_id, password);
        if (su != null) {
            WebUser wu = new WebUser();
            wu.setLoginID(su.mod.getStr("login_id"));
            wu.setEmpName(su.mod.getStr("user_name"));
            wu.setEmpID(su.mod.getStr("emp_id"));
            wu.setUser_type(su.mod.getStr("user_TYPE"));
            //
            String[] roles = getUserRole(wu.getEmpID());
            wu.setRoles(roles);
            request.getSession().setAttribute("USERINFO", wu);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 验证帐号密码
     *
     * @param request
     * @return
     */
    public boolean validateUserPwd(HttpServletRequest request, HttpServletResponse response) {
        String login_id = ParamUtil.getString(request, "username");
        //String password = Md5.MD5(ParamUtil.getString(request, "password"));
        String password = ParamUtil.getString(request, "password");
        String sql = "select * from sys_user where login_id=? and user_pwd=?";
        SysUser su = SysUser.dao.findFirst(sql, login_id, password);
        if (su != null) {
            String empid = su.getStr("emp_id", "");
            WebUser wu = new WebUser();
            wu.setLoginID(su.mod.getStr("login_id"));
            wu.setEmpName(su.mod.getStr("user_name"));
            wu.setEmpID(su.mod.getStr("emp_id"));
            wu.setUser_type(su.mod.getStr("user_TYPE"));
            //
            String[] roles = getUserRole(wu.getEmpID());
            wu.setRoles(roles);
            CookieUtil.setCookie(response, "EMPID", String.valueOf(empid));
            request.getSession().setAttribute("USERINFO", wu);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 验证帐号密码
     *
     * @param request
     * @return
     */
    public boolean validateUserPwdMd5(HttpServletRequest request, HttpServletResponse response) {
        String login_id = ParamUtil.getString(request, "username");
        String password = Md5.MD5(ParamUtil.getString(request, "password"));
        String sql = "select * from sys_user where login_id=? and user_pwd=?";
        SysUser su = SysUser.dao.findFirst(sql, login_id, password);
        if (su != null) {
            String empid = su.getStr("emp_id", "");
            WebUser wu = new WebUser();
            wu.setLoginID(su.mod.getStr("login_id"));
            wu.setEmpName(su.mod.getStr("user_name"));
            wu.setEmpID(su.mod.getStr("emp_id"));
            wu.setUser_type(su.mod.getStr("user_TYPE"));
            //
            String[] roles = getUserRole(wu.getEmpID());
            wu.setRoles(roles);
            CookieUtil.setCookie(response, "EMPID", String.valueOf(empid));
            request.getSession().setAttribute("USERINFO", wu);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 验证帐号密码
     *
     * @param request
     * @return
     */
    public boolean validateUserPwdJwt(HttpServletRequest request) {
        String login_id = ParamUtil.getString(request, "username");
        String password = Md5.MD5(ParamUtil.getString(request, "password"));
        String sql = "select * from sys_user where login_id=? and user_pwd=?";
        SysUser su = SysUser.dao.findFirst(sql, login_id, password);
        if (su != null) {
            WebUser wu = new WebUser();
            String empid = su.getStr("emp_id", "");
            String loginid = su.mod.getStr("login_id");
            wu.setLoginID(su.mod.getStr("login_id"));
            wu.setEmpName(su.mod.getStr("user_name"));
            wu.setEmpID(su.mod.getStr("emp_id"));
            wu.setUser_type(su.mod.getStr("user_TYPE"));
            //
            String[] roles = getUserRole(wu.getEmpID());
            wu.setRoles(roles);
            String rols = Arrays.toString(roles);
            JwtUtil.JwtSubject js = new JwtUtil.JwtSubject(empid, loginid, rols);
            wu.setJwt(JwtUtil.createJWT(String.valueOf(empid), js, EXPRESS_LOGIN_TIME));

            request.getSession().setAttribute("USERINFO", wu);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 验证帐号密码
     *
     * @param emp_id
     * @param passwd
     * @return
     */
    public JsonResult validateUserPwd(String emp_id, String passwd) {
        passwd = Md5.MD5(passwd);
        String sql = "select * from sys_user where emp_id=? and user_pwd=?";
        SysUser su = SysUser.dao.findFirst(sql, emp_id, passwd);
        if (su != null) {
            String empid = su.getStr("emp_id");
            String loginid = su.mod.getStr("login_id");
            String rols = Arrays.toString(getUserRole(emp_id));
            JwtUtil.JwtSubject js = new JwtUtil.JwtSubject(empid, loginid, rols);
            return JsonResult.n(0, "密码正确", JwtUtil.createJWT(emp_id, js, EXPRESS_LOGIN_TIME));
        } else {
            return JsonResult.n(9, "密码错误");
        }
    }


    /**
     * 验证帐号密码
     *
     * @param login_id
     * @param passwd
     * @return
     */
    public JsonResult validateUserPwdJwt(String login_id, String passwd, String ip) {
        JsonResult jr = JsonResult.n();
        String password = Md5.MD5(passwd);
        System.out.println(password);
        String sql = "select * from sys_user where login_id=? and user_pwd=?";
        SysUser su = SysUser.dao.findFirst(sql, login_id, password);
        if (su != null) {
            String empid = su.getStr("emp_id", "");
            int deptid = su.getInt("dept_id", 0);
            int braid = su.getInt("bra_id", 0);
            int lock_tag = su.mod.getInt("lock_tag");
            int del_tag = su.mod.getInt("del_tag");
            String loginid = su.mod.getStr("login_id");
            String posts = su.mod.getStr("user_post");
            if (lock_tag == 1) {
                jr.setCode(9).setMsg("帐号已锁定").setExtra("登陆帐号:" + loginid);
            } else if (del_tag == 1) {
                jr.setCode(9).setMsg("帐号已删除").setExtra("登陆帐号:" + loginid);
            } else if (su.mod.getStr("login_id").length() > 0) {
                WebUser wu = new WebUser();
                wu.setLoginID(su.mod.getStr("login_id"));
                wu.setEmpName(su.mod.getStr("user_name"));
                wu.setEmpID(su.mod.getStr("emp_id"));
                wu.setUser_type(su.mod.getStr("user_type"));
                //
                String[] roles = getUserRole(wu.getEmpID());
                wu.setRoles(roles);
                String rols = "|" + StringUtil.getString(roles, "|") + "|";
                posts = StringUtil.replace(posts, ",", "|");
                posts = "|" + posts + "|";
                long lastlogin = System.currentTimeMillis();
                JwtUtil.JwtSubject js = new JwtUtil.JwtSubject(empid, deptid, loginid, rols, lastlogin).setId(UUIDHex.getUUIDHex());
                js.setPosts(posts);
                js.setOrgid(braid);
                wu.setJwt(JwtUtil.createJWT(js.getId(), js, EXPRESS_LOGIN_TIME));
                jr.setCode(0).setMsg("登陆成功").setExtra(JwtUtil.createJWT(wu.getEmpID(), js, EXPRESS_LOGIN_TIME));
            } else {
                jr.setCode(9).setMsg("密码错误");
            }
        } else {
            jr.setCode(9).setMsg("密码错误");
        }
        return jr;
    }


    /**
     * 初始化帐号
     *
     * @param empid
     * @return
     */
    public JsonResult validateUserPwdJwt(String empid, String ip) {
        JsonResult jr = JsonResult.n();
        SysUser su = SysUser.dao.findById(empid);
        if (su != null) {
            int deptid = su.mod.getInt("dept_id");
            int lock_tag = su.mod.getInt("lock_tag");
            int del_tag = su.mod.getInt("del_tag");
            String loginid = su.mod.getStr("login_id");
            String posts = su.mod.getStr("user_post");
            if (lock_tag == 1) {
                jr.setCode(9).setMsg("帐号已锁定").setExtra("登陆帐号:" + loginid);
            } else if (del_tag == 1) {
                jr.setCode(9).setMsg("帐号已删除").setExtra("登陆帐号:" + loginid);
            } else if (su.mod.getStr("login_id").length() > 0) {
                WebUser wu = new WebUser();
                wu.setLoginID(su.mod.getStr("login_id"));
                wu.setEmpName(su.mod.getStr("user_name"));
                wu.setEmpID(su.mod.getStr("emp_id"));
                wu.setUser_type(su.mod.getStr("user_type"));
                //
                String[] roles = getUserRole(wu.getEmpID());
                wu.setRoles(roles);
                String rols = "|" + StringUtil.getString(roles, "|") + "|";
                posts = StringUtil.replace(posts, ",", "|");
                posts = "|" + posts + "|";
                long lastlogin = System.currentTimeMillis();
                JwtUtil.JwtSubject js = new JwtUtil.JwtSubject(empid, deptid, loginid, rols, lastlogin).setId(UUIDHex.getUUIDHex());
                js.setPosts(posts);
                wu.setJwt(JwtUtil.createJWT(js.getId(), js, EXPRESS_LOGIN_TIME));
                jr.setCode(0).setMsg("登陆成功").setExtra(JwtUtil.createJWT(wu.getEmpID(), js, EXPRESS_LOGIN_TIME));
            } else {
                jr.setCode(9).setMsg("密码错误");
            }
        } else {
            jr.setCode(9).setMsg("帐号不存在");
        }
        return jr;
    }

    /**
     * 验证帐号密码
     *
     * @return
     */
    @Admins(roles = "administrator", name = "", log = false)
    public JsonResult validateUserJwt(String emp_id) {
        String sql = "select * from sys_user where emp_id=?";
        SysUser su = SysUser.dao.findFirst(sql, emp_id);
        if (su != null) {
            String empid = su.getStr("emp_id");
            int deptid = su.mod.getInt("dept_id");
            int braid = su.mod.getInt("bra_id");
            String loginid = su.mod.getStr("login_id");
            WebUser wu = new WebUser();
            wu.setLoginID(su.mod.getStr("login_id"));
            wu.setEmpName(su.mod.getStr("user_name"));
            wu.setEmpID(su.mod.getStr("emp_id"));
            wu.setUser_type(su.mod.getStr("user_TYPE"));
            //
            String[] roles = getUserRole(wu.getEmpID());
            wu.setRoles(roles);
            String rols = "|" + StringUtil.getString(roles, "|") + "|";
            JwtUtil.JwtSubject js = new JwtUtil.JwtSubject(empid, loginid, rols);
            js.setOrgid(braid);
            wu.setJwt(JwtUtil.createJWT(String.valueOf(empid), js, EXPRESS_LOGIN_TIME));
            return JsonResult.n(0, "密码正确", JwtUtil.createJWT(wu.getEmpID(), js, EXPRESS_LOGIN_TIME));
        } else {
            return JsonResult.n(9, "密码不正确");
        }
    }

    /**
     * @param emp_id
     * @return
     */
    private String[] getUserRole(String emp_id) {
        String sql = "select role_id from sys_user_role where emp_id=?";
        List list = SysUser.dao.find(sql, emp_id);
        if (list == null) list = new ArrayList();
        String[] s = new String[list.size()];
        for (int k = 0; k < list.size(); k++) {
            SysUser su = (SysUser) list.get(k);
            s[k] = su.mod.getStr("role_id", "");
        }
        return s;
    }

    /**
     * 记录登陆日志
     *
     * @param request
     * @param code
     * @param msg
     * @param loginid
     */
    public void saveLog(HttpServletRequest request, int code, String msg, String loginid) {
        String ip = ClientUtil.getIp(request);
        String os = ClientUtil.getClientOS(request);
        String browser = ClientUtil.getClientBrowser(request);
        SysWorklog worklog = new SysWorklog();
        worklog.set("log_result", code == 0 ? 1 : 2).set("log_title", msg).set("log_time", new Date());
        worklog.set("log_ip", ip).set("log_os", os).set("log_browser", browser).set("log_desc", "");
        worklog.set("log_iparea", IpKit.n().getAddress(ip));
        worklog.set("log_type", 99).set("emp_id", 0).set("user_name", "").set("login_id", loginid);

        SysWorkLogUtil.n().saveLog(worklog);
    }

    /**
     * 修改密码
     *
     * @param data
     */
    public Results ChangePwd(Datas data, String empid) {
        Results results = Results.n(9);
        if (data == null) return results.setMsg("传入的参数不正确");
        String oldPassword1 = Base64.decodeStr(data.getBaseStr("oldPassword", ""));//
        String password1 = Base64.decodeStr(data.getBaseStr("password"));//
        String repassword1 = Base64.decodeStr(data.getBaseStr("repassword"));//
        String password = Aes.aesDecrypt(password1);
        String oldPassword = Aes.aesDecrypt(oldPassword1);
        String repassword = Aes.aesDecrypt(repassword1);
        if (password.length() < 8) return results.setMsg("新密码必须是8位及以上");
        if (!Pwd.match_Aa18(password)) return results.setMsg("新密码必须是大小写字母数字组合");
        if (!password.equals(repassword)) return results.setMsg("两次密码不一致");
        if (empid.length() < 3) return results.setMsg("您未登陆");
        SysUser su = SysUser.dao.findById(empid);
        if (su == null) return results.setMsg("用户不存在");
        if (!Md5.MD5(oldPassword).equals(su.get("user_pwd"))) return results.setMsg("旧密码不正确");
        if (su.set("user_pwd", Md5.MD5(password)).update()) {
            return results.setCode(0).setMsg("密码修改成功");
        } else {
            return results.setMsg("密码修改失败");
        }
    }


    /**
     * 验证登陆
     *
     * @param request
     * @param response
     */
    public Results ValidateLogin(HttpServletRequest request, HttpServletResponse response) {
        Results results = Results.n(9).setMsg("登陆失败");
        ///////////////////////解密//////////////////////////////////////////
        String aeskey = CookieUtil.getSecureCookie(request, "aeskey");
        String aesiv = CookieUtil.getSecureCookie(request, "aesiv");
        String username = Aes.aesCBCDecode(request.getParameter("username"), aeskey, aesiv);
        String password = Aes.aesCBCDecode(request.getParameter("password"), aeskey, aesiv);
        //////////////////////////////////////////////////////////////////////////

        boolean vCode = true;//默认验证码通过
        //////////////////////////////验证码/////////////////////////////
        String VALIDATECODE = (String) request.getSession().getAttribute("VALIDATECODE");
        if ("|admin|wuyang|".indexOf("|" + username + "|") > -1 || ConfigUtil.isWindows()) {
            vCode = true;
        } else {
            VALIDATECODE = VALIDATECODE.toUpperCase();
            String vercode = ParamUtil.getString(request, "vercode", "");
            if (!vercode.toUpperCase().equals(VALIDATECODE)) {
                log.error("验证码错误,正确[" + VALIDATECODE + "],输入[" + vercode + "]");
                return results.setMsg("验证码错误");
            }
        }
        ////////////////清除验证码
        request.getSession().setAttribute("VALIDATECODE", null);
        /////////////////////////////验证码结束//////////////////
        if (vCode) {
//            String password1 = Base64.decodeStr(request.getParameter("password"));
//            String password = Aes.aesDecrypt(password1);
            if (StrUtil.isBlank(password)) return results.setMsg("无效的密码信息");
            if (password.length() < 8) return results.setMsg("密码必须是8位及以上");
            if (!Pwd.match_Aa18(password)) return results.setMsg("密码必须是大小写字母数字组合");

            String ip = ClientUtil.getIp(request);
            String os = ClientUtil.getClientOS(request);
            String browser = ClientUtil.getClientBrowser(request);
            JsonResult jr = LoginUtil.getInstance().validateUserPwdJwt(username, password, ip);
            System.out.println(jr.toJson());
            if (jr.getCode() == 0) {
                String jwt = jr.getExtra();
                WebSite.setJwt(response, jwt);
                request.getSession().setAttribute("VALIDATECODE", null);
                ////////////////////写登陆日志/////////////////
                String sessid = JwtUtil.getJwtInfo(jwt).getId();
                String empid = JwtUtil.getJwtInfo(jwt).getUserid();
                String loginid = JwtUtil.getJwtInfo(jwt).getUsername();
                /////////////////////写在线用户////////////////////////
                SysOnlineUtil.n().saveLogin(sessid, empid, ip, os, browser);//
                results.setCode(0).setMsg("登录成功");
            } else {
                results.setMsg(jr.getMsg());
            }
        }
        /////记录日志
        LoginUtil.n().saveLog(request, results.getCode(), results.getMsg(), username);
        return results;
    }

    public static void main(String[] arg) {
        System.out.println(Md5.MD5("kyy18215592304"));
    }
}
